<template>
  <div class="goods-add">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item to="/goods">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="mt_20px">
      <el-alert title="添加商品信息" type="info" show-icon center></el-alert>

      <el-steps
        :active="active"
        finish-status="success"
        :process-status="active === 5 ? 'success' : ''"
        align-center
        class="mt_20px"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 基本信息内容区域 -->
      <div v-show="active === 0">
        <el-form ref="jbxxForm" :model="jbxx.form.data" :rules="jbxx.form.rules">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="jbxx.form.data.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input-number
              v-model="jbxx.form.data.goods_price"
              style="width: 100%;"
              :controls="false"
              :precision="2"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input-number
              v-model="jbxx.form.data.goods_weight"
              style="width: 100%;"
              :controls="false"
              :precision="2"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input-number
              v-model="jbxx.form.data.goods_number"
              style="width: 100%;"
              :controls="false"
              :precision="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <goods-cate-cascader
              style="width: 100%;"
              v-model="jbxx.form.data.goods_cat"
              :allow-checked-levels="[3]"
            ></goods-cate-cascader>
          </el-form-item>
        </el-form>
      </div>
      <!-- 商品参数内容区域 -->
      <div v-show="active === 1">
        <div class="my_20px" v-for="v in spcs.list" :key="v.attr_id">
          <div class="mb_20px">{{ v.attr_name }}</div>
          <div>
            <el-checkbox-group v-model="v.attr_val_arr_selected">
              <el-checkbox
                v-for="(v2, i) in v.attr_val_arr"
                :key="i"
                :label="v2"
                border
              ></el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <!-- 商品属性内容区域 -->
      <div v-show="active === 2">
        <div class="my_20px" v-for="v in spsx.list" :key="v.attr_id">
          <div class="mb_20px">{{ v.attr_name }}</div>
          <div>
            <el-input v-model="v.attr_vals"></el-input>
          </div>
        </div>
      </div>
      <!-- 商品图片内容区域 -->
      <div v-show="active === 3">
        <el-upload
          class="my_20px"
          :action="sptp.uploadURL"
          :headers="sptp.uploadHeaders"
          list-type="picture-card"
          :on-success="handleSuccessOfSptp"
          :on-preview="handlePreviewOfSptp"
          :on-remove="handleRemoveOfSptp"
        >
          <template #default>
            <i class="el-icon-plus"></i>
          </template>
        </el-upload>
      </div>
      <!-- 商品内容内容区域 -->
      <div v-show="active === 4">
        <div class="spnr_box">
          <quill-editor v-model="spnr.form.data.goods_introduce"></quill-editor>
        </div>
      </div>
      <!-- 完成内容区域 -->
      <div v-show="active === 5">
        <el-row class="my_20px">
          <el-col :span="18" :offset="3">
            <el-alert
              :title="`商品添加成功，${countdown}秒后自动跳转到列表页`"
              type="success"
              description="文字说明文字说明文字说明文字说明文字说明文字说明"
              show-icon
              :closable="false"
              center
            >
            </el-alert>
          </el-col>
        </el-row>
      </div>

      <div class="btn_box" v-if="active !== 5">
        <el-button @click="prevStep" :disabled="active === 0">上一步</el-button>
        <el-button @click="nextStep">{{ active === 4 ? '提交' : '下一步' }}</el-button>
      </div>
    </el-card>

    <el-dialog title="图片预览" :visible.sync="sptp.previewDialog.visible">
      <template #default>
        <el-image :src="sptp.previewDialog.url" fit="cover"></el-image>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import GoodsCateCascader from '@/components/GoodsCateCascader.vue';

// 倒计时的定时器id
let intervalId = null;

export default {
  name: 'GoodsAdd',
  components: { GoodsCateCascader },
  data() {
    return {
      // 基本信息
      jbxx: {
        form: {
          data: {
            goods_name: '',
            goods_price: 0,
            goods_weight: 0,
            goods_number: 0,
            goods_cat: [],
          },
          rules: {
            goods_name: [
              { required: true, message: '请输入商品名称', trigger: ['change', 'blur'] },
            ],
            goods_price: [
              { required: true, message: '请输入商品价格', trigger: ['change', 'blur'] },
              {
                type: 'number',
                min: 0.01,
                max: 99999999.99,
                message: '商品价格区间必须是0.01 ~ 99,999,999.99之间',
                trigger: ['change', 'blur'],
              },
            ],
            goods_weight: [
              { required: true, message: '请输入商品重量', trigger: ['change', 'blur'] },
              {
                type: 'number',
                min: 0.01,
                max: 99999999.99,
                message: '商品重量区间必须是0.01 ~ 99,999,999.99之间',
                trigger: ['change', 'blur'],
              },
            ],
            goods_number: [
              { required: true, message: '请输入商品数量', trigger: ['change', 'blur'] },
              {
                type: 'integer',
                min: 1,
                max: 99999999,
                message: '商品数量区间必须是1 ~ 99,999,999之间',
                trigger: ['change', 'blur'],
              },
            ],
            goods_cat: [{ required: true, message: '请选择商品分类', trigger: ['change', 'blur'] }],
          },
        },
      },
      // 商品参数
      spcs: {
        list: [],
        form: {
          data: {
            attrs: [],
          },
        },
      },
      // 商品属性
      spsx: {
        list: [],
        form: {
          data: {
            attrs: [],
          },
        },
      },
      // 商品图片
      sptp: {
        // 预览对话框相关的数据
        previewDialog: {
          visible: false,
          url: '',
        },
        uploadURL: `${this.__apis.baseURL}upload`,
        uploadHeaders: {
          Authorization: window.localStorage.getItem('token'),
        },
        form: {
          data: {
            pics: [],
          },
        },
      },
      // 商品内容
      spnr: {
        form: {
          data: {
            goods_introduce: '',
          },
        },
      },
      // 倒计时跳转，单位：秒
      countdown: 3,
      // 当前进行中的步骤：0为第一步
      active: 0,
    };
  },
  computed: {
    // 商品分类id
    cat_id() {
      const arr = this.jbxx.form.data.goods_cat;
      const len = arr.length;
      if (len > 0) {
        return arr[len - 1];
      }
      return 0;
    },
  },
  // watch: {
  //   '$route.path': function () {
  //     console.log('监听不到路由的变化,因为,只要路由一变,该组件就会被销毁');
  //   },
  // },
  methods: {
    // 上传成功时的回调
    handleSuccessOfSptp(res, file, fileList) {
      // console.log(res, file, fileList, 'handleSuccessOfSptp');
      const { status, msg } = res.meta;
      if (status !== 200) {
        return this.$message.error(msg);
      }
      this.sptp.form.data.pics.push({ pic: res.data.tmp_path });
    },
    // 预览图片
    handlePreviewOfSptp(file) {
      console.log(file, 'handlePreview');
      this.sptp.previewDialog.url = file.url;
      this.sptp.previewDialog.visible = true;
    },
    // 删除图片
    handleRemoveOfSptp(file, fileList) {
      console.log(file, fileList, 'handleRemove');
      // 过滤出不是这张图片的其他图片
      this.sptp.form.data.pics = this.sptp.form.data.pics.filter(
        (v) => v.pic !== file.response.data.tmp_path
      );
    },
    // 上一步
    prevStep() {
      if (this.active > 0) {
        this.active--;
      }
    },
    // 下一步
    async nextStep() {
      if (this.active === 0) {
        // 第一步：基本信息时，点击了下一步
        try {
          // 验证表单
          await this.$refs.jbxxForm.validate();
        } catch (err) {
          return;
        }

        // 只有当没加载过时，才发请求
        if (!this.spcs.list.loaded) {
          // 通过表单验证，则发请求获取商品动态参数列表数据
          const { data: res } = await this.__apis.goodsParams.list({
            cat_id: this.cat_id,
            sel: 'many',
          });
          const { status, msg } = res.meta;
          if (status !== 200) {
            return this.$message.error(msg);
          }

          // 如果需要添加自定义的数据属性，那么应该事先处理好，再赋值到data上，否则数据驱动视图有问题
          res.data.forEach((v) => {
            if (v.attr_vals.trim() === '') {
              v.attr_val_arr = [];
            } else {
              v.attr_val_arr = v.attr_vals.split(',');
            }
            // 用来保存已选中的选项
            v.attr_val_arr_selected = [];
          });

          // 是否已加载标记
          res.data.loaded = true;

          // 列表数据赋值
          this.spcs.list = res.data;
        }
      } else if (this.active === 1) {
        // 第二步：商品参数时，点击了下一步
        // 处理表单数据
        this.spcs.form.data.attrs = this.spcs.list.map((v) => {
          return { attr_id: v.attr_id, attr_value: v.attr_val_arr_selected.join(',') };
        });

        // 只有当没加载过时，才发请求
        if (!this.spsx.list.loaded) {
          // 请求商品属性列表数据
          const { data: res } = await this.__apis.goodsParams.list({
            cat_id: this.cat_id,
            sel: 'only',
          });
          const { status, msg } = res.meta;
          if (status !== 200) {
            return this.$message.error(msg);
          }
          // 是否已加载标记
          res.data.loaded = true;
          // 列表数据赋值
          this.spsx.list = res.data;
        }
      } else if (this.active === 2) {
        // 第三步：商品属性时，点击了下一步
        // 处理表单数据
        // eslint-disable-next-line
        this.spsx.form.data.attrs = this.spsx.list.map(({ attr_id, attr_vals }) => ({
          attr_id,
          attr_value: attr_vals,
        }));
      } else if (this.active === 4) {
        // 提交整个表单，处理最终表单数据
        const data = {
          ...this.jbxx.form.data,
          goods_cat: this.jbxx.form.data.goods_cat.join(','),
          ...this.spnr.form.data,
          ...this.sptp.form.data,
          attrs: [...this.spcs.form.data.attrs, ...this.spsx.form.data.attrs],
        };
        const { data: res } = await this.__apis.goods.add(data);
        const { status, msg } = res.meta;
        if (status !== 201) {
          return this.$message.error(msg);
        }

        // 倒计时跳转
        intervalId = setInterval(() => {
          this.countdown--;
          if (this.countdown === 0) {
            clearInterval(intervalId);
            this.$router.go(-1);
          }
        }, 1000);
      }

      if (this.active < 5) {
        this.active++;
      }
    },
  },
  // 路由器跳转到其他路由时，该组件会被销毁
  // 组件销毁的钩子，一般在这里清楚当前页面中创建的定时器
  destroyed() {
    clearInterval(intervalId);
  },
};
</script>

<style lang="less" scoped>
.goods-add {
  .el-card {
    // 样式穿透，/deep/ 后面的选择器，不会受scoped的影响
    /deep/ .el-input__inner {
      text-align: left;
    }
    .btn_box {
      display: flex;
      justify-content: space-between;
    }

    .spnr_box {
      margin: 20px 0 60px 0;

      .quill-editor {
        height: 200px;
      }
    }
  }
}
</style>
